<template>
    <div class="page setting-page">
        <div class="setting-title" style="width:1000px;">
            <span>选择光伏组件</span>
            <div class="term-info">
                <div class="term-title">{{form.name}}</div>
                <div class="term-type">{{form.locationType | filterType(form.stationType)}}</div>
            </div>
        </div>
        <div style="width:1000px;overflow: hidden">
            <div class="setting-form" style="width:560px;float:left;">
                <el-form ref="settingForm" label-width="140px" class="setting-form" size="small" label-position="left" :model="form" :rules="rules" style="width:100%">
                    <div class="form-div">
                        <el-form-item label="厂商" prop="companyId">
                            <el-select  placeholder="请选择" style="width:300px" v-model="form.companyId" @change="changeCompanyId">
                                <el-option :value="item.id" :key="item.id" :label="item.name"  v-for="item in companyList"></el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="晶体类型" prop="moduleType">
                            <el-select  placeholder="请选择" style="width:300px" v-model="form.moduleType" @change="changeModuleType">
                                <el-option  :value="item.id" :key="item.id" :label="item.label" v-for="item in moduleTypeList"></el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="组件型号" prop="componentId">
                            <el-select  placeholder="请选择" style="width:300px" v-model="form.componentId" @change="changeComponentId('edit')">
                                <el-option :value="item.id" :key="item.id" :label="item.moduleModel" v-for="item in componentList"></el-option>
                            </el-select>
                        </el-form-item>
                        <div class="chart-div form-div" style="margin-bottom:20px;padding-left:140px" v-if="form.componentId">
                            <el-link type="info" @click="showDialogVisible1">组件功率衰减曲线</el-link>
                            <el-link type="info" @click="showDialogVisible2">组件I-V曲线</el-link>
                            <el-link type="info" @click="dialogVisible3 = true">组件参数</el-link>
                        </div>
                        <el-form-item label="电厂设计容量" prop="powerPlantCapacity">
                            <el-input style="width:130px" v-model="form.powerPlantCapacity" @change="cuntComponent"></el-input>
                            <el-select  placeholder="请选择" style="width:130px" v-model="form.powerPlantCapacityType" @change="changePowerPlantCapacityType">
                                <el-option value="kWp" label="kWp" key="kWp"></el-option>
                                <el-option value="MWp" label="MWp" key="MWp"></el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="组件设计使用数量" prop="componentNum" >
                            <el-input style="width:130px"  v-model="form.componentNum" disabled></el-input>
                            <span style="padding-left:10px">个</span>
                        </el-form-item>
                        <el-form-item label="系统直流端耐压" prop="dcWithstandVoltage" >
                            <el-select  placeholder="请选择" style="width:130px" v-model="form.dcWithstandVoltage">
                                <el-option value="1000" label="1000" key="1000"></el-option>
                                <el-option value="1500" label="1500" key="1500"></el-option>
                            </el-select>
                            <span style="padding-left:10px">V</span>
                        </el-form-item>
                    </div>
                </el-form>
            </div>
            <div class="syimg1">
                <div><img src="../static/img/syimg1.png"/></div>
                <div class="syimg1-title">
                    <div>{{cutCompany ? cutCompany.name : '-'}}</div>
                    <div style="font-weight: bold;font-size:16px">{{cutComponent && cutComponent.moduleModel? cutComponent.moduleModel : '-'}}</div>
                    <div style="margin-top:10px">长：{{curComponentInfo && curComponentInfo.l_c? curComponentInfo.l_c+'cm' : '-'}}</div>
                    <div>宽：{{curComponentInfo && curComponentInfo.w_c? curComponentInfo.w_c+'cm' : '-'}}</div>
                    <div>厚：{{curComponentInfo &&curComponentInfo.moduleModel ? curComponentInfo.moduleModel+'cm' : '-'}}</div>
                    <div>组件面积：{{curComponentInfo && curComponentInfo.a_c? curComponentInfo.a_c+'m^2' : '-'}}</div>
                    <div>重量：{{curComponentInfo && curComponentInfo.moduleModel? curComponentInfo.moduleModel : '-'}}</div>
                    <div>功率：{{curComponentInfo && curComponentInfo.p_stc? curComponentInfo.p_stc+'wp' : '-'}}</div>
                </div>
            </div>
        </div>
        <div class="setting-page-bottom">
            <div class="img"><img src="../static/img/logo.png"/> </div>
            <div class="right-link-div">
                <div class="link-btn active">选择光伏组件</div>
                <div class="link-btn">支架组件排布</div>
                <div class="link-btn">现场布置及分析</div>
                <div class="prev-btn" style="width:44px"></div>
                <div class="next-btn"><el-button type="primary" @click="toSettingInverter" :loading="btnLoading2">下一步</el-button></div>
            </div>
        </div>

        <!--组件功率衰减曲线-->
        <el-dialog
                title="组件功率衰减曲线"
                :visible.sync="dialogVisible1"
                width="750px">
            <div id="myChart" :style="{width: '750px', height: '300px'}"></div>
        </el-dialog>

        <!--组件I-V曲线-->
        <el-dialog
                title="组件I-V曲线"
                :visible.sync="dialogVisible2"
                width="750px">
            <div id="myChart2" :style="{width: '750px', height: '300px'}"></div>
        </el-dialog>

        <!--组件参数-->
        <el-dialog
                title="组件参数"
                :visible.sync="dialogVisible3"
                width="750px">
            <div class="params-div">
                <el-row class="params-heard">
                    <el-col :span="16" class="param-left">参数名称</el-col>
                    <el-col :span="8" class="param-right">参数值</el-col>
                </el-row>
                <div class="params-main">
                    <el-row class="params-row" v-for="(item,index) in componentParamsList" :key="index">
                        <el-col :span="16" class="param-left">{{item.name}}</el-col>
                        <el-col :span="8" class="param-right">{{item.value}}</el-col>
                    </el-row>
                </div>
            </div>
        </el-dialog>
    </div>
</template>

<script>
    import {
        getCompanyList,
        getComponentList,
        updateProject,
        getComponentInfo,
        getProjectDetail,
        getWucanshu,
        getDetailWithName,getSlopeYear} from '@/api/index.js';
    export default {
        name: 'settingPhotovoltaic',
        data() {
            const isvalidatePowerPlantCapacity = (rule, value, callback) => {
                let reg =/^\d{1,5}(?:\.\d{1,2})?$/;
                if (!reg.test(value)) {
                    callback(new Error('最长可填写5位整数及2位小数'))
                }else{
                    callback()
                }
            };
            const isvalidateModuleType = (rule, value, callback) => {
                if (!value) {
                    callback(new Error('请选择晶体类型'))
                }else{
                    callback()
                }
            };
            return {
                form:{
                    companyId:null,
                    moduleType:null,
                    componentId:null,
                    powerPlantCapacity:null,//电厂容量
                    powerPlantCapacityType:'kWp',//容量单位
                    componentNum:null,//组件数量
                    dcWithstandVoltage:null,//系统直流端耐压
                },
                rules:{
                    companyId:[{required: true, message: '请选择厂商', trigger: 'change'}],
                    moduleType:[{required: true, validator: isvalidateModuleType, trigger: 'change'}],
                    componentId:[{required: true, message: '请选择组件类型', trigger: 'change'}],
                    powerPlantCapacity:[{required: true, validator: isvalidatePowerPlantCapacity, trigger: 'blur'}],
                    componentNum:[{required: true, message: '请输入组件数量', trigger: 'blur'}],
                    dcWithstandVoltage:[{required: true, message: '请选择系统直流端耐压', trigger: 'change'}],
                },
                type:'',
                dialogVisible:false,
                activeName:'first',
                moduleTypeList:[
                    {label:'单晶',id:'MONO_C_SI'},
                    {label:'多晶',id:'MULTI_C_SI'},
                    {label:'薄膜',id:'THIN_FILM'},
                    {label:'碲化镉',id:'CDTE'},
                    {label:'铜铟镓硒',id:'CIGS'}
                ],
                id:this.$route.query.id,//项目ID
                companyList:[],//组件厂商列表
                componentList:[],//组件列表
                btnLoading:false,
                btnLoading2:false,
                curComponentInfo:{},//当前组件详情
                isDown2:true,
                componentParamsList:[],
                dialogVisible1:false,
                dialogVisible2:false,
                dialogVisible3:false,
                cutCompany:null,
                cutComponent:null,

            }
        },
        watch:{
            '$route'(to,from){
                if(from.name=='home'){
                    this.init()
                }
            }
        },
        filters: {
            filterType(locationType, stationType) {
                if (locationType == 'ground' && stationType == 'online') {
                    return '并网地面电站'
                } else if (locationType == 'ground' && stationType == 'offline') {
                    return '离网网地面电站'
                } else if (locationType == 'roof' && stationType == 'online') {
                    return '并网网屋顶电站'
                } else if (locationType == 'roof' && stationType == 'offline') {
                    return '离网网屋顶电站'
                }
            },
        },
        methods: {

            //下一步
            toSettingInverter(){
                this.$refs['settingForm'].validate((valid) => {
                    if (valid) {
                        this.btnLoading2 = true;
                        this.saveProject().then(()=>{
                            this.btnLoading2 = false;
                            this.$router.push({name:'settingBracket',query: {id: this.id},});
                        }).catch(()=>{
                            this.btnLoading2 = false;
                        });
                    }
                })
            },


            //保存工程
            saveProject(){
                let data = {};
                data.id = this.id;
                data.companyId = this.form.companyId;
                data.componentId = this.form.componentId;
                data.moduleType = this.form.moduleType;
                data.powerPlantCapacity = this.form.powerPlantCapacity;
                data.powerPlantCapacityType = this.form.powerPlantCapacityType;
                data.componentNum = this.form.componentNum;
                data.dcWithstandVoltage = this.form.dcWithstandVoltage;
                return updateProject(data).then((res)=>{
                    this.$message({
                        message: '工程文件保存成功',
                        type: 'success'
                    });
                })
            },

            //显示组件功率衰减曲线
            showDialogVisible1(){
                this.dialogVisible1 = true;
                setTimeout(()=>{
                    this.drawLine();
                },300)

            },

            //显示组件IV曲线
            showDialogVisible2(){
                this.dialogVisible2 = true;
                setTimeout(()=>{
                    this.getIVlineData();
                },300)

            },




            //画组件功率衰减曲线
            drawLine(){
                let myChart = this.$echarts.init(document.getElementById('myChart'));
                // 绘制图表
                myChart.setOption({
                    title: {
                        text: '组件功率衰减曲线',
                        x:'center' ,
                        textStyle: {
                            fontSize: 14,
                            fontStyle: 'normal',
                            fontWeight: 'normal',
                        },
                    },
                    tooltip : {
                        trigger: 'axis',
                    },
                    xAxis: {
                        type: 'category',
                        data: [0, 5, 10, 15, 20, 25],
                        name:'组件工作时间（年）',
                        nameLocation:'middle',
                        nameGap:40
                    },
                    yAxis: {
                        type: 'value',
                        name:'组件额定输出功率（%）',
                        nameLocation:'middle',
                        nameGap:50
                    },
                    series: [{
                        data: [100, 96, 92, 88, 84, 80],
                        type: 'line',
                        label: {
                            normal: {
                                show: true,
                                position: 'top',
                                formatter:function(a){
                                    return a.value+"%";
                                }
                            }
                        },
                        smooth: true
                    }]
                });
            },

            //画组件IV曲线
            drawIVLine(x,y,Isc,Voc,Imp){
                let myChart = this.$echarts.init(document.getElementById('myChart2'))
                // 绘制图表
                myChart.setOption({
                    title: {
                        text: '组件I-V曲线',
                        x:'center' ,
                        textStyle: {
                            fontSize: 14,
                            fontStyle: 'normal',
                            fontWeight: 'normal',

                        },
                    },
                    tooltip : {
                        trigger: 'axis',
                    },
                    xAxis: {
                        type: 'category',
                        data: x,
                        name:'组件输出电压（V）',
                        nameLocation:'middle',
                        nameGap:40,
                        axisLabel: {
                            formatter: function (val) {
                                return parseFloat(val).toFixed()
                            }
                        }

                    },
                    yAxis: {
                        type: 'value',
                        name:'组件输出电流（A）',
                        nameLocation:'middle',
                        nameGap:50
                    },

                    series: [{
                        data: y,
                        type: 'line',
                        smooth: true,
                        showAllSymbol:true,
                        symbolSize:1,
                        label:{
                            show:true,
                            position:'top',
                            formatter:function (params) {
                                if (params.value == Isc) {
                                    return '短路电流：'+params.data.toFixed(2)
                                }else if (parseFloat(params.name) == Voc){
                                    return '开路电压：'+parseFloat(params.name).toFixed(2)
                                }else if (params.value == Imp){
                                    return '最大功率点电压：'+params.data.toFixed(2)
                                }else {
                                    return ''
                                }
                            },


                        }
                    }]
                });
            },

            //获取组件参数
            getComponentParamsList(){
                getDetailWithName({componentId:this.form.componentId}).then((res)=>{
                    this.componentParamsList = res;
                })
            },

            //获取组件厂商列表
            getCompanyListData(){
               return  getCompanyList({companyType:'COMPONENT'}).then((res)=>{
                    this.companyList = res
                });
            },

            //获取组件列表
            getComponentListData(){
                if(this.form.companyId && this.form.moduleType){ //如果厂商与晶体类型都有
                    return getComponentList({companyId:this.form.companyId,moduleType:this.form.moduleType}).then((res)=>{
                                this.componentList = res
                            })
                }else{
                    return Promise.reject(1);
                }
            },

            //获取组件详情
            getComponentInfoData(){
                return getComponentInfo({componentId:this.form.componentId}).then((res)=>{
                    this.curComponentInfo = res;
                })
            },

            //切换厂商
            changeCompanyId(){
                this.componentList = [];
                this.form.moduleType = null;
                this.form.componentId = null;
                this.powerPlantCapacity = null;
                this.componentNum = null;
                this.cutComponent = null;
                this.getComponentListData();
                this.findCompanyName();
            },



            //切换晶体类型
            changeModuleType(){
                this.componentList = [];
                this.form.componentId = null;
                this.powerPlantCapacity = null;
                this.componentNum = null;
                this.cutComponent = null;
                this.getComponentListData();
            },

            //切换组件
            changeComponentId(type){
                this.powerPlantCapacity = null;
                this.componentNum = null;
                this.getComponentInfoData().then(()=>{
                    if(type != 'new'){ //不是回显进，算组件数量,计算间距
                        this.cuntComponent();
                    }
                    this.getComponentParamsList();
                    this.findComponentName();
                });
            },

            //找出厂家名
            findCompanyName(){
                this.cutCompany = this.companyList.find((el)=>{
                    return  el.id == this.form.companyId
                });
            },

            //找出组件名
            findComponentName(){
                this.cutComponent = this.componentList.find((el)=>{
                    return  el.id == this.form.componentId
                });

            },

            //切换电厂容量单位
            changePowerPlantCapacityType(){
                this.cuntComponent();
            },

            //计算组件数量
            cuntComponent(){
                let reg =/^\d{1,5}(?:\.\d{1,2})?$/;
                let flag = reg.test(this.form.powerPlantCapacity)
                if (this.form.componentId && flag){
                    if (this.form.powerPlantCapacityType == 'MWp'){
                        this.form.componentNum = Math.ceil(this.form.powerPlantCapacity*1000000/this.curComponentInfo.p_stc);
                    }else {
                        this.form.componentNum = Math.ceil(this.form.powerPlantCapacity*1000/this.curComponentInfo.p_stc);
                    }
                }
            },

            //获取组件IV曲线
            getIVlineData(){
                let data= {};
                data.a = this.curComponentInfo.a_ref;//曲线拟合因子
                data.IL = this.curComponentInfo.i_l_ref;//光电流
                data.Io = this.curComponentInfo.i_o_ref;//二极管反向饱和电流
                data.Rs = this.curComponentInfo.r_s;//串联电阻
                data.Rsh = this.curComponentInfo.r_sh_ref;//并联电阻
                getWucanshu(data).then((res)=>{
                    let x = res.Vx;
                    let y = res.Iy;
                    let reverseX = x.reverse();
                    let reverseY = y.reverse();
                    let i = reverseX.findIndex((el)=>{
                        return el !=0;
                    });
                    reverseX.splice(0,i);
                    reverseY.splice(0,i);
                    x = reverseX.reverse();
                    y = reverseY.reverse();
                    this.drawIVLine(x,y,res.Isc,res.Voc,res.Imp);
                })
            },

            //获取工程组件信息
            getProjectDetailData(){
                getProjectDetail({projectId:this.$route.query.id}).then((res)=>{
                    this.form = Object.assign({
                        moduleType:null,}, res);
                    this.form.powerPlantCapacityType = this.form.powerPlantCapacityType ? this.form.powerPlantCapacityType : 'kWp';
                    this.getCompanyListData().then(()=>{
                        if(this.form.companyId){
                            this.findCompanyName();
                        }
                    });
                    this.getComponentListData().then(()=>{
                        if(this.form.componentId){
                            this.changeComponentId('new');
                        }
                    });

                    setTimeout(()=>{
                        this.$refs['settingForm'].clearValidate()
                    },500)

                })
            },
            //初始化页面数据
            init(){
                this.getProjectDetailData();
            }

        },
        created() {
            this.init()
        },
        beforeRouteEnter(to, form, next) {
            $("html").css({'overflowY':'scroll'})
            next()
        },

        beforeRouteLeave(to, form, next) {
            $("html").css({'overflowY':'auto'})
            next()
        },
    }
</script>

<style>
    #allmap {
        height: 300px;
        width: 100%;
        overflow: hidden;
    }

    #r-result {
        width: 100%;
        font-size: 14px;
        margin-bottom:20px
    }
</style>



